package com.qianniu.napi.admin.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.service.IConfigService;
import com.qianniu.napi.admin.service.INavService;
import com.qianniu.napi.admin.service.IRedisService;
import com.qianniu.napi.common.util.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 配置表
 * </p>
 *
 * @author chenxuebin
 * @since 2018-09-08
 */
@Controller
public class ConfigController {

    private static final Logger logger = LoggerFactory.getLogger(ConfigController.class);

    @Autowired
    private IConfigService configService;
    @Autowired
    private INavService navService;
    @Autowired
    private IRedisService redisService;

    //@RequiresPermissions("admin:config:view")
    @RequestMapping("admin/config/index")
    public String index(Model model) {

        if (ObjectUtil.getUserType() == 99) {
            List<Config> configs = configService.selectList(new EntityWrapper<Config>().setSqlSelect("code,name"));
            model.addAttribute("configs", configs);
        }else if(ObjectUtil.getMpid()==null||ObjectUtil.getMpid()==0){
            List<Config> configs = configService.selectList(new EntityWrapper<Config>().setSqlSelect("code,name").eq("mid",ObjectUtil.getMid()));
            model.addAttribute("configs", configs);
        }else{
            List<Config> configs = configService.selectList(new EntityWrapper<Config>().setSqlSelect("code,name").eq("mpid",ObjectUtil.getMpid()));
            model.addAttribute("configs", configs);
        }
        Wrapper<Config> wrapper = new EntityWrapper<Config>().setSqlSelect("distinct type,typename")
                .eq("mpid",ObjectUtil.getMpid()).isNotNull("type");

        List<Config> types = configService.selectList(wrapper);

        model.addAttribute("types", types);
//        model.addAttribute("typesall", typesall);

        MerchantApp mapp = redisService.getMApp(ObjectUtil.getMpid());
        model.addAttribute("version", mapp.getVersion());

        return "admin/config";
    }

    //@RequiresPermissions("admin:config:view")
    @RequestMapping("admin/config/hyindex")
    public String hyindex(Model model) {

        return "admin/confighy";
    }

    //@RequiresPermissions("admin:config:view")
    @RequestMapping("/admin/config/list")
    @ResponseBody
    public Page<Config> list(@RequestParam(value = "limit", required = false) int limit,
                             @RequestParam(value = "status", required = false) String status,
                             @RequestParam(value = "search", required = false) String search,
                             @RequestParam(value = "offset", required = false) int offset,
                             @RequestParam(value = "order", required = false) String order) {
        User user = ObjectUtil.getSessionUser();
        Wrapper<Config> wrapper = new EntityWrapper<Config>()
                .eq("mpid", user.getMpid());
        if(!Strings.isNullOrEmpty(status))
            wrapper.eq("type",status);

        if (!Strings.isNullOrEmpty(search))
            wrapper.like("name", search);

        wrapper.orderBy("id", order.equalsIgnoreCase("asc") ? true : false);
        Page<Config> page = configService.selectPage(new Page<Config>(offset / limit + 1, limit), wrapper);
        return page;
    }

    //    @RequiresPermissions("admin:config:view")
    @RequestMapping("/admin/config/hylist")
    @ResponseBody
    public Page<Config> hylist(@RequestParam(value = "limit", required = false) int limit,
                             @RequestParam(value = "status", required = false) Integer status,
                             @RequestParam(value = "search", required = false) String search,
                             @RequestParam(value = "offset", required = false) int offset,
                             @RequestParam(value = "order", required = false) String order) {
        User user = ObjectUtil.getSessionUser();
        Wrapper<Config> wrapper = new EntityWrapper<Config>()
                .eq("mpid", user.getMpid())
                .eq("type","hangyefenlei");
        if (!Strings.isNullOrEmpty(search))
            wrapper.like("name", search);

        wrapper.orderBy("id", order.equalsIgnoreCase("asc") ? true : false);
        Page<Config> page = configService.selectPage(new Page<Config>(offset / limit + 1, limit), wrapper);
        return page;
    }

    //    @RequiresPermissions("admin:config:add")
    @RequestMapping("/admin/config/add")
    public String add(@Valid Config bean, BindingResult bindingResult,Model model) {
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            return null;
        }
        Wrapper<Config> wrapper = new EntityWrapper<Config>().eq("code", bean.getType());
        Wrapper<Config> wrappercot = new EntityWrapper<Config>()
                .eq("type", bean.getType())
                .eq("mpid", ObjectUtil.getMpid());

        Config pconfig = configService.selectOne(wrapper);
        Integer cout = configService.selectCount(wrappercot);
        if (pconfig != null) {
            bean.setPid(pconfig.getId());
            bean.setType(bean.getType());
            bean.setTypename(pconfig.getName());
            bean.setPcode(pconfig.getCode());
            bean.setLevel(pconfig.getLevel()==null?1:pconfig.getLevel()+1);
            bean.setSort(cout+1);
        }else{
            bean.setLevel(1);
            bean.setType(bean.getCode());
            bean.setTypename(bean.getName());
            bean.setSort(1);
        }

        wrapper = new EntityWrapper<Config>();
        wrapper.where("type={0} and code={1}  and mpid={2}", bean.getType(), bean.getCode(), ObjectUtil.getMpid());
        List<Config> existList = configService.selectList(wrapper);
        if (existList != null && existList.size() > 0) {
            model.addAttribute("msg", "该配置项重复");
            return "admin/config";
        }

        bean.setCreatetime(new Date());
        bean.setUid(ObjectUtil.getUid());
        bean.setMid(ObjectUtil.getMid());
        bean.setMpid(ObjectUtil.getMpid());
        if (ObjectUtil.getIsAdmin() == 1) {
            bean.setIsSystem(1);
        } else {
            bean.setIsSystem(0);
        }
        bean.insert();
        return "redirect:index";
    }

    @RequestMapping("/admin/config/getConfigById")
    @ResponseBody
    public Config getConfigById(Long id) {
        Config config = configService.selectById(id);
        return config;
    }

    //    @RequiresPermissions("admin:config:delete")
    @RequestMapping("/admin/config/deleteOne")
    @ResponseBody
    public int deleteOne(Long id) {
        boolean isSucc = configService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    //    @RequiresPermissions("admin:config:delete")
    @RequestMapping("/admin/config/delete")
    @ResponseBody
    public int deleteBatchIds(@RequestParam(value = "ids[]") List<Integer> ids) {
        boolean isSucc = configService.deleteBatchIds(ids);
        return isSucc ? 1 : 0;
    }

    //    @RequiresPermissions("admin:config:modify")
    @RequestMapping("/admin/config/changeState")
    @ResponseBody
    public String changeState(long id, int state) {
        Config bean = new Config();
        bean.setId(id);
        bean.setState(state);
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        configService.updateById(bean);
        return "success";
    }

    //    @RequiresPermissions("admin:config:modify")
    @RequestMapping("/admin/config/modify")
    public String update(Config bean) {
        Wrapper<Config> wrapper = new EntityWrapper<Config>();
        wrapper.eq("type",bean.getType()).eq("code",bean.getCode())
                .ne("id",bean.getId());
        if(ObjectUtil.getMpid()!=null)wrapper.ne("mpid",ObjectUtil.getMpid());
        if(ObjectUtil.getMid()!=null)wrapper.ne("mid",ObjectUtil.getMid());

        List<Config> existList = configService.selectList(wrapper);
        if (existList != null && existList.size() > 0) {
            logger.debug("同一类型下编码重复");
            return null;
        }

        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        boolean isSuccc = configService.updateById(bean);
        if (isSuccc) {
            return "redirect:index";
        }
        return "error";
    }

    @RequestMapping("/admin/config/setnav")
    @ResponseBody
    public Jinfo setnav(Nav bean) {
        Jinfo jinfo = new Jinfo();

        Wrapper<Nav> wrapper = new EntityWrapper<Nav>();
        wrapper.where("nvalue={0} and ntype=3", bean.getNvalue())
                .eq("mpid",ObjectUtil.getMpid());
        List<Nav> existList = navService.selectList(wrapper);
        if (existList != null && existList.size() > 0) {
            jinfo.setCode(1);
            jinfo.setMsg("已存在该分类导航");
            return jinfo;
        }

        wrapper = new EntityWrapper<Nav>();
        wrapper.setSqlSelect("max(sort) as sort");
        wrapper.eq("mpid",ObjectUtil.getMpid());
        Nav maxnav = navService.selectOne(wrapper);
        bean.setSort(maxnav!=null?maxnav.getSort()+1:1);
        bean.setCreatetime(new Date());
        bean.setUid(ObjectUtil.getUid());
        bean.setMid(ObjectUtil.getMid());
        bean.setMpid(ObjectUtil.getMpid());

        bean.insert();
        return jinfo;
    }

    @RequestMapping("/admin/config/checknav")
    @ResponseBody
    public Jinfo checknav(String nvalue) {
        Jinfo jinfo = new Jinfo();

        Wrapper<Nav> wrapper = new EntityWrapper<Nav>();
        wrapper.where("nvalue={0} and ntype=3", nvalue)
        .eq("mpid",ObjectUtil.getMpid());
        List<Nav> existList = navService.selectList(wrapper);
        if (existList != null && existList.size() > 0) {
            jinfo.setCode(1);
            jinfo.setMsg("已存在该分类导航");
            return jinfo;
        }
        return jinfo;
    }

}
